package cn.tedu.xzs.admin.questionmanagement.service.impl;

import cn.tedu.xzs.admin.questionmanagement.dao.persist.repository.AnswerRepository;
import cn.tedu.xzs.admin.questionmanagement.dao.persist.repository.QuestionRepository;
import cn.tedu.xzs.admin.questionmanagement.ex.ServiceException;
import cn.tedu.xzs.admin.questionmanagement.pojo.entity.Answer;
import cn.tedu.xzs.admin.questionmanagement.pojo.entity.Question;
import cn.tedu.xzs.admin.questionmanagement.pojo.param.AnswerAddNewParam;
import cn.tedu.xzs.admin.questionmanagement.pojo.param.QuestionAddNewParam;
import cn.tedu.xzs.admin.questionmanagement.pojo.vo.QuestionVO;
import cn.tedu.xzs.admin.questionmanagement.service.QuestionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService{
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private AnswerRepository answerRepository;

    @Override
    public void addNew(QuestionAddNewParam questionAddNewParam, List<AnswerAddNewParam> params) {
        //添加question
        //查询questionId
        //添加answer
        Question question = new Question();
        BeanUtils.copyProperties(questionAddNewParam, question);
        question.setId(null);
        question.setCreateTime(new Date());
        question.setUpdateTime(new Date());
        question.setDel(0);
        int i = questionRepository.addNew(question);
        if (i != 1) {
            throw new RuntimeException("添加问题失败");
        }

        //TODO
        Long latestQuestionId = questionRepository.getLatestQuestionId();
        Question typeById = questionRepository.getTypeById(latestQuestionId);
        Integer questionType = typeById.getType();
        for (int j = 0; j < params.size(); j++) {
            addSingleChooseQuestion(params.get(j),latestQuestionId,questionType);
        }
        if (typeById==null){
            throw new ServiceException("题型异常，创编试题失败");
        }
}

    @Override
    public PageInfo<QuestionVO> getQuestionVOPage(Integer pageNum, Integer pageSize) {
        return questionRepository.getQuestionVOPage(pageNum,pageSize);
    }


    private void addSingleChooseQuestion(AnswerAddNewParam param,Long latestQuestionId,Integer type) {
        Answer answer = new Answer();
        BeanUtils.copyProperties(param, answer);
        answer.setQuestionId(latestQuestionId);
        answer.setType(type);
        answerRepository.addNew(answer);
    }
}
